package com.dormitory123.millet.service.Impl;

import com.dormitory123.millet.dao.Impl.OrderDaoImpl;
import com.dormitory123.millet.dao.Impl.OrderItemDaoImpl;
import com.dormitory123.millet.dao.Impl.PhoneDaoImpl;
import com.dormitory123.millet.dao.OrderDao;
import com.dormitory123.millet.dao.OrderItemDao;
import com.dormitory123.millet.dao.PhoneDao;
import com.dormitory123.millet.pojo.*;
import com.dormitory123.millet.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yanhuanzhan
 * @date 2022/1/6 - 19:43
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private PhoneDao phoneDao = new PhoneDaoImpl();
    @Override
    public Order createOrder(Cart cart, Integer userId) {
        String orderId = System.currentTimeMillis() +""+ userId;
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time = format.format(date);
        Order order = new Order(orderId,time,cart.getTotalPrice(),cart.getTotalCount(),0,userId);
        orderDao.createOrder(order);
       //创建订单项
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId,cartItem.getImgPath());
            orderItemDao.createOrderItem(orderItem);
            //更新商品信息
            Phone phone = phoneDao.queryPhoneById(cartItem.getId());
            //更新销量
            phone.setSales(phone.getSales()+cartItem.getCount());
            //更新库存
            phone.setStock(phone.getStock()-cartItem.getCount());
            phoneDao.updatePhone(phone);
        }
        return order;
    }

    @Override
    public List<Order> queryOrdersByUserId(Integer userId) {

        List<Order> orders= orderDao.queryOrdersByUserId(userId);
        List<Order> reverseOrders = new ArrayList<>();
        //进行逆序排列，使最后下单的订单显示到前面
        for (int i = orders.size() - 1; i >= 0; i--) {
            reverseOrders.add(orders.get(i));
        }
        return reverseOrders;
    }

    @Override
    public List<OrderItem> queryOrderItemByOrderId(String orderId) {
        return orderItemDao.queryOrderItemsByOrderId(orderId);
    }

    @Override
    public Map<String, List<OrderItem>> queryOrderItems(List<Order> orders) {
        Map<String, List<OrderItem>> listMap = new LinkedHashMap<>();
        for (Order order : orders) {
            List<OrderItem> orderItems = orderItemDao.queryOrderItemsByOrderId(order.getOrderId());
            listMap.put(order.getOrderId(), orderItems);
        }
        return listMap;
    }

}
